#!/usr/local/bin/python3
# -*- coding: utf-8 -*-

"""
@File    : __init__.py.py
@Author  : different
@Time    : 2021-8-7 9:56
@Desc    : db对象

"""
from functools import wraps

from flask import (current_app, request, redirect, g)
from flask_login import current_user
from flask_login.config import EXEMPT_METHODS
from flask_sqlalchemy import SQLAlchemy

db = SQLAlchemy()


def login_required(func):
    @wraps(func)  # 保留源信息，本质是endpoint装饰，否则修改函数名很危险
    def decorated_view(*args, **kwargs):
        if request.method in EXEMPT_METHODS:
            return func(*args, **kwargs)
        elif current_app.config.get('LOGIN_DISABLED'):
            return func(*args, **kwargs)
        elif not current_user.is_authenticated:
            return redirect('/login')
        return func(*args, **kwargs)

    return decorated_view


def auth_management(func):
    """
    非管理员用户的修改权限
    :param func:
    :return:
    """

    @wraps(func)
    def decorated_view(*args, **kwargs):
        if g.user.is_superuser:
            return func(*args, **kwargs)
        else:
            return redirect(request.referrer)

    return decorated_view
